/**
 * 泛娱区块链 - Login
 * http://menger.me
 * @author: zaric
 * @creation time: 2018-12-07
 */

'use strict';
import React from 'react';
import {Image, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import NavigationBar from '../../component/navigation/NavigationBar';
import Container from '../../component/common/Container';
import TextInput from '../../component/common/TextInput';
import Button from '../../component/common/Button';
import {isMobile} from '../../util/Tool';
import {inject, observer} from 'mobx-react';
import Images from '../../asset';
import SegmentedView from '../../component/segmented/SegmentedView';
import VerificationCode from '../../component/common/VerificationCode';
import ServicesApi from '../../config/ServicesApi';
import JShareModule from 'jshare-react-native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import {HorizontalLine} from "../../component/common/CommonLine";

@inject('appStore', 'loginStore')
@observer
class Login extends React.Component {

    constructor(props) {
        super(props);
        this.inputData = {
            memberPhone: '',
            memberPassword: '',
        };
        this.state = {codeOpen: false};
    }

    componentDidMount() {

    }

    componentWillUnmount() {

    }

    _onPressLogin = async () => {
        let params = {
            title: '温馨提示',
            detail: '',
            actions: [
                {
                    title: '确定', onPress: () => {
                    }
                }
            ]
        };
        if (!this.inputData['memberPhone']) {
            params['detail'] = '请检查手机号输入是否正确';
            AlertManager.show(params)
        } else {
            const {loginStore} = this.props;
            const params = {
                user_account: this.inputData['memberPhone'],
                user_password: this.inputData['memberPassword'],
            };
            const result = await loginStore.gotoLogin(ServicesApi.USER_LOGIN, params);
            // console.log('登录返回------------>', result);
            if (result.code === StatusCode.SUCCESS_CODE) {
                ToastManager.show('登录成功');
                RouterHelper.reset('', 'Tab');
            } else {
                ToastManager.show(result.dec || 'error')
            }
        }
    };

    _onPressRegister = async () => {
        let params = {
            title: '温馨提示',
            detail: '',
            actions: [
                {
                    title: '确定', onPress: () => {
                    }
                }
            ]
        };
        if (!this.inputData['memberPhone']) {
            params['detail'] = '请检查手机号输入是否正确';
            AlertManager.show(params)
        } else if (!this.inputData['code'] || this.inputData['code'].length < 4) {
            params['detail'] = '请检查验证码是否输入正确';
            AlertManager.show(params)
        } else if (this.inputData['memberPassword'].length === 0) {
            params['detail'] = '请输入密码';
            AlertManager.show(params)
        } else if (this.inputData['memberPassword'] !== this.inputData['memberPasswordTwo']) {
            params['detail'] = '两次输入的密码不一致';
            AlertManager.show(params)
        } else {
            const {loginStore} = this.props;
            const params = {
                user_phone: this.inputData['memberPhone'],
                user_password: this.inputData['memberPassword'],
                captcha: this.inputData['code'],
                type: 'phone_register',
            };

            const result = await loginStore.postRequest(ServicesApi.USER_REGISTER, params);
            if (result.code === 0) {
                const params = {
                    title: '温馨提示',
                    detail: '注册成功，返回登录！',
                    actions: [
                        {
                            title: '确定', onPress: () => {
                                this.segmentedRef.changeScrollPage(0, false)
                                this.pwdInput.text = ''
                                this.pwdTwoInput.text = ''
                                this.codeInput.text = ''
                                this.phoneInput.text = ''
                            }
                        }
                    ]
                };
                AlertManager.show(params)
            } else {
                ToastManager.show(result.msg)
            }
        }
    };

    _onPressVer = async () => {
        let params = {
            title: '温馨提示',
            detail: '',
            actions: [
                {
                    title: '确定', onPress: () => {
                    }
                }
            ]
        };
        if (!this.inputData['memberPhone']) {
            params['detail'] = '请检查手机号输入是否正确';
            AlertManager.show(params)
        } else {
            const {loginStore} = this.props;
            const params = {phone: this.inputData['memberPhone'], sms_model: 'register_sms_model'};
            const result = await loginStore.postRequest(ServicesApi.COMMON_SEND_SMS, params);
            if (result.code === 0) {
                ToastManager.show('获取验证码成功!');
                this.setState({codeOpen: true})
            } else {
                ToastManager.show(result.msg)
            }
            // console.log(result)
        }
    };

    _onPressNavigate = (title, component, params) => {
        RouterHelper.navigate(title, component, params);
    };

    //第三方登录、注册
    _onPressThirdRegisterAndLogin = (type) => {//0 :QQ  1:微信
        // RouterHelper.navigate('', 'BindingPhone',);
        // return;
        let platform;
        let params;
        if (type === 0) {
            platform = 'qq'
        } else {
            platform = 'wechat'
        }

        JShareModule.authorize({platform}, async (map) => {
            // console.log('三方------->',map);
            //获取三方用户资料
            let param = {
                platform: type === 0 ? 'qq' : 'wechat_session'
            };
            JShareModule.getSocialUserInfo(param, async (infoMap) => {
                // console.log('info',infoMap);
                if (type === 0) {
                    const authData = {
                        access_token: map.token,
                        unionid: 1,
                    };
                    const url = `${ServicesApi.GET_AUTH_QQ}?access_token=${map.token}&unionid=1`;
                    const result = await Services.get(ServicesApi.GET_AUTH_QQ, authData, {type: 'qq_login'});
                    // console.log('qqAuth------------>',result);
                    const formatAuth = result.substring(10, result.length - 3);
                    // console.log('formatAuth',formatAuth);
                    params = {
                        type: 'qq_login',
                        // captcha: '1token',
                        // station: 'app',
                        qq_token: JSON.parse(formatAuth).unionid,
                        qq_nickname: infoMap.name,
                        qq_img: infoMap.imageUrl,
                        qq_app_openID: map.openId,
                        qq_sex: JSON.parse(infoMap.originData).gender ? JSON.parse(infoMap.originData).gender : '男',
                    }
                } else {
                    params = {
                        type: 'wx_login',
                        // captcha: '1token',
                        // station: 'app',
                        wx_token: JSON.parse(map.originData).unionid,
                        wx_nickname: infoMap.name,
                        wx_img: infoMap.imageUrl,
                        wx_app_openID: map.openId,
                        wx_sex: infoMap.gender,
                    }
                }
                this.requestAuthorize(params)
            }, (errorCode) => {
                // console.log("errorCode: " + errorCode);
            });
        }, (errorCode) => {
            // console.log('errorCode---->', errorCode);
            let {error_message} = errorCode.description;
            ToastManager.show(error_message);
        });
    };

    requestAuthorize = async (params) => {
        // console.log(map)
        const {loginStore} = this.props;
        const result = await loginStore.thirdLogin(ServicesApi.USER_LOGIN, params);
        if (result.code === StatusCode.SUCCESS_CODE) {
            if (result.data.user_phone) { //已绑定手机号，进入主页
                RouterHelper.reset('', 'Tab');
            } else { //未绑定手机号，进入绑定
                RouterHelper.navigate('', 'BindingPhone', {
                    type: params.type,
                    user_id: result.data.user_id,
                    token: params.type === 'wx_login' ? result.data.wx_token : result.data.qq_token
                })
            }
        } else {
            ToastManager.show(result.dec || 'error');
        }
    };
    _onChangeText = (key, text) => {
        this.inputData[key] = text
    };
    _onStopInterval = () => {
        this.setState({codeOpen: false})
    };

    //渲染登录视图
    _renderLogin = () => {
        return (
            <KeyboardAwareScrollView
                style={styles.content}
                keyboardShouldPersistTaps={'handled'}
            >
                <View style={styles.content}>
                    <HorizontalLine style={styles.titleLine}/>
                    <View style={styles.loginInputStyle}>
                        {/*<Text title={styles.hintText}>+86</Text>*/}
                        {/*<Image style={styles.titleIconStyle} source={Images.icon_right_arrow}/>*/}
                        <TextInput
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text) => this._onChangeText('memberPhone', text)}
                            placeholder={'手机号'}
                            keyboardType={'numeric'}
                        />
                    </View>
                    <View style={styles.pwdStyle}>

                        <TextInput
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            placeholder={'登录密码'}
                            onChangeText={(text) => this._onChangeText('memberPassword', text)}
                            secureTextEntry={true}
                        />

                    </View>
                    <TouchableOpacity
                        style={styles.forgetStyle}
                        onPress={() => this._onPressNavigate('忘记密码', 'ChangePwd', {page_flag: 'forget'})}
                    >
                        <Text style={styles.forgetPwd}>忘记密码</Text>
                    </TouchableOpacity>
                    <Button style={styles.button} title={'登 录'} onPress={this._onPressLogin}/>
                    {this.renderExtendLogin()}

                </View>
            </KeyboardAwareScrollView>
        )
    };

    //渲染注册视图
    _renderRegister = () => {
        const {codeOpen} = this.state
        return (
            <KeyboardAwareScrollView
                style={styles.content}
                keyboardShouldPersistTaps={'handled'}
            >
                <View style={styles.content}>
                    <HorizontalLine style={styles.titleLine}/>
                    <View style={styles.loginInputStyle}>
                        {/*<Text title={styles.hintText}>+86</Text>*/}
                        {/*<Image style={styles.titleIconStyle} source={Images.icon_right_arrow}/>*/}
                        <TextInput
                            ref={(v) => this.phoneInput = v}
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text) => this._onChangeText('memberPhone', text)}
                            placeholder={'手机号'}
                            keyboardType={'numeric'}
                        />
                    </View>
                    <View style={[styles.loginInputStyle, {flexDirection: 'row'}]}>
                        <TextInput
                            ref={(v) => this.codeInput = v}
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text) => this._onChangeText('code', text)}
                            placeholder={'验证码'}
                            keyboardType={'numeric'}
                        />
                        <VerificationCode
                            open={codeOpen}
                            onStopInterval={this._onStopInterval}
                            onPress={this._onPressVer}
                            style={styles.getCodeStyle}
                        />
                    </View>
                    <View style={styles.pwdStyle}>
                        <TextInput
                            ref={(v) => this.pwdInput = v}
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            placeholder={'输入密码'}
                            onChangeText={(text) => this._onChangeText('memberPassword', text)}
                            secureTextEntry={true}
                        />

                    </View>
                    <View style={styles.pwdStyle}>
                        <TextInput
                            ref={(v) => this.pwdTwoInput = v}
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            placeholder={'确认密码'}
                            onChangeText={(text) => this._onChangeText('memberPasswordTwo', text)}
                            secureTextEntry={true}
                        />

                    </View>
                    <Button style={styles.button} title={'提交注册'} onPress={this._onPressRegister}/>

                </View>
            </KeyboardAwareScrollView>

        )
    };

    renderExtendLogin = () => {
        return (
            <View style={styles.registerBottomStyle}>
                <View style={styles.flexCenter}>
                    <View style={styles.bottomLine}/>
                    <Text style={styles.bottomHint}>第三方登录</Text>
                    <View style={styles.bottomLine}/>
                </View>
                <View style={styles.flexMarginCenter}>
                    <TouchableOpacity onPress={() => this._onPressThirdRegisterAndLogin(0)}>
                        <Image style={styles.qqStyle} source={Images.icon_qq}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => this._onPressThirdRegisterAndLogin(1)}>
                        <Image style={[styles.wxStyle, {marginLeft: 51}]} source={Images.icon_wechat}/>
                    </TouchableOpacity>
                </View>
            </View>
        );
    };

    render() {
        return (
            <Container
                style={styles.container}
                keyboardShouldPersistTaps={true}
            >
                <NavigationBar
                    title={'北链泛娱'}
                    iconStyle={{tintColor: '#fff'}}
                    titleStyle={{color: '#fff'}}
                    statusBarStyle={'light-content'}
                    style={styles.nav}
                    renderLeftAction={null}
                />
                <SegmentedView
                    ref={(v) => this.segmentedRef = v}
                    justifyItem={'fixed'}
                    showSegmentedBar={true}
                    scrollEnabled={true}
                    indicatorLineWidth={3}
                    indicatorLineColor={Theme.themeColor}
                    indicatorPositionPadding={0}
                    style={styles.headerTitle}
                    keyboardShouldPersistTaps={'always'}
                >
                    <View
                        title={'登录'}
                        style={styles.segmentedItem}
                        titleStyle={styles.titleStyle}
                        activeTitleStyle={styles.activeTitleStyle}
                    >
                        {this._renderLogin()}
                    </View>
                    <View
                        title={'注册'}
                        style={styles.segmentedItem}
                        titleStyle={styles.titleStyle}
                        activeTitleStyle={styles.activeTitleStyle}
                    >
                        {this._renderRegister()}
                    </View>
                </SegmentedView>
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        // paddingTop: 94,
        backgroundColor: '#fff',
    },
    nav: {
        backgroundColor: Theme.themeColor
    },
    headerTitle: {
        flex: 1,
        paddingTop: 68,
    },
    segmentedItem: {
        flex: 1,
    },

    flexCenter: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    flexMarginCenter: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 15
    },

    titleStyle: {
        color: '#333',
        fontSize: FontSize(16),
    },
    activeTitleStyle: {
        fontSize: FontSize(16),
        color: Theme.themeColor,
    },

    content: {
        flex: 1,
    },
    titleIconStyle: {
        width: 6,
        height: 12,
        marginHorizontal: 5,
        resizeMode: 'contain',
    },
    loginInputStyle: {
        paddingVertical: 12,
        marginHorizontal: 30,
        // backgroundColor: 'red',
        borderBottomWidth: 1,
        borderBottomColor: '#ececec',
    },
    pwdStyle: {
        // height: 60,
        marginHorizontal: 30,
        paddingVertical: 12,
        borderBottomWidth: 1,
        borderBottomColor: '#ececec',
        // backgroundColor: 'blue',
    },
    hintText: {
        fontSize: FontSize(15),
        color: '#333'
    },
    inputStyle: {
        flex: 1,
        padding: 0,
        fontSize: FontSize(15),
        // height: 44,
        // backgroundColor: 'red',
    },
    titleLine: {
        backgroundColor: '#ececec',
        height: 1,
        marginLeft: 30,
        marginRight: 30,
        marginTop: 8,
        marginBottom: 37,
    },
    inputLine: {
        backgroundColor: '#ececec',
        height: 1,
        marginRight: 30,
    },
    forgetStyle: {
        paddingTop: 8,
        paddingBottom: 8,
        alignItems: 'flex-end',
        marginRight: 30,
    },
    forgetPwd: {
        fontSize: FontSize(13),
        color: "#ffcc9b"
    },
    button: {
        marginTop: 25,
        marginHorizontal: 30,
        backgroundColor: Theme.themeColor,
        color: '#fff'
    },
    bottomStyle: {
        flex: 1,
        marginTop: 155,
        alignItems: 'center',
        marginLeft: 15,
        marginRight: 15,
    },
    registerBottomStyle: {
        marginTop: 30,
        marginBottom: 20,
        marginHorizontal: 30,
        alignItems: 'center',
    },
    bottomLine: {
        flex: 1,
        height: 1,
        backgroundColor: '#ececec',
    },
    bottomHint: {
        color: '#a6a6a6',
        marginHorizontal: 20,
        fontSize: FontSize(12)
    },
    qqStyle: {
        width: 26,
        height: 29,
    },
    wxStyle: {
        width: 31,
        height: 31,
    },
    getCodeStyle: {
        // borderLeftWidth: 1,
        // borderColor: '#ffefe0',
        // paddingLeft: 16,
        // color: '#ffcc9b',
        // marginRight: 30,
    },
});

export default Login